{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 初始化"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### clone代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!git clone https://github.com/modelscope/modelscope-agent.git"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 安装特定依赖"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cd modelscope-agent && pip install -r requirements.txt"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 本地配置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.chdir('modelscope-agent/demo')\n",
    "\n",
    "import sys\n",
    "sys.path.append('../')"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### API_KEY管理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入DASHSCOPE_API_KEY\n",
      "请输入ModelScope Token\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "print('请输入DASHSCOPE_API_KEY')\n",
    "os.environ['DASHSCOPE_API_KEY'] = input()\n",
    "print('请输入ModelScope Token')\n",
    "os.environ['MODELSCOPE_API_TOKEN'] = input()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 构建agent A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-03-22 16:59:33,259 - modelscope - INFO - PyTorch version 2.2.1 Found.\n",
      "2024-03-22 16:59:33,261 - modelscope - INFO - Loading ast index from /Users/yangkun/.cache/modelscope/ast_indexer\n",
      "2024-03-22 16:59:33,370 - modelscope - INFO - Loading done! Current index file version is 1.13.1, with md5 2a227e922142dcd4a5e0097bf19d8a77 and a total number of 972 components indexed\n"
     ]
    }
   ],
   "source": [
    "from modelscope_agent.agents import RolePlay\n",
    "\n",
    "role_template = '你扮演一个明星人物专家，了解从古至今的电影明星'\n",
    "\n",
    "llm_config = {\n",
    "    'model': 'qwen-max', \n",
    "    'model_server': 'dashscope',\n",
    "    }\n",
    "\n",
    "function_list = []\n",
    "\n",
    "bot1 = RolePlay(function_list=function_list, llm=llm_config, instruction=role_template)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 构建memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-03-22 16:59:48,535 - modelscope - WARNING - Model revision not specified, use revision: v1.1.0\n",
      "2024-03-22 16:59:48,788 - modelscope - INFO - initiate model from /Users/yangkun/.cache/modelscope/hub/damo/nlp_gte_sentence-embedding_chinese-base\n",
      "2024-03-22 16:59:48,788 - modelscope - INFO - initiate model from location /Users/yangkun/.cache/modelscope/hub/damo/nlp_gte_sentence-embedding_chinese-base.\n",
      "2024-03-22 16:59:48,791 - modelscope - INFO - initialize model from /Users/yangkun/.cache/modelscope/hub/damo/nlp_gte_sentence-embedding_chinese-base\n",
      "2024-03-22 16:59:50,135 - modelscope - WARNING - No preprocessor field found in cfg.\n",
      "2024-03-22 16:59:50,135 - modelscope - WARNING - No val key and type key found in preprocessor domain of configuration.json file.\n",
      "2024-03-22 16:59:50,136 - modelscope - WARNING - Cannot find available config to build preprocessor at mode inference, current config: {'model_dir': '/Users/yangkun/.cache/modelscope/hub/damo/nlp_gte_sentence-embedding_chinese-base'}. trying to build by task and model information.\n",
      "2024-03-22 16:59:50,162 - modelscope - INFO - cuda is not available, using cpu instead.\n",
      "2024-03-22 16:59:50,165 - modelscope - WARNING - No preprocessor field found in cfg.\n",
      "2024-03-22 16:59:50,165 - modelscope - WARNING - No val key and type key found in preprocessor domain of configuration.json file.\n",
      "2024-03-22 16:59:50,165 - modelscope - WARNING - Cannot find available config to build preprocessor at mode inference, current config: {'model_dir': '/Users/yangkun/.cache/modelscope/hub/damo/nlp_gte_sentence-embedding_chinese-base', 'sequence_length': 128}. trying to build by task and model information.\n"
     ]
    }
   ],
   "source": [
    "from modelscope_agent.memory import MemoryWithRetrievalKnowledge\n",
    "\n",
    "DEFAULT_UUID_HISTORY = \"/root/you_data/you_config/history\"\n",
    "storage_path = \"/root/you_data/you_config/config\"\n",
    "memory_history_path = os.path.join(DEFAULT_UUID_HISTORY, 'default_user.json')\n",
    "memory_agent_name = 'default_memory'\n",
    "memory = MemoryWithRetrievalKnowledge(storage_path=storage_path,\n",
    "        name=memory_agent_name,\n",
    "        memory_path=memory_history_path,\n",
    "        )"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 执行agent A"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "history = memory.get_history()\n",
    "input_text = \"介绍一下成龙和李连杰\"\n",
    "response = bot1.run(input_text, remote=False, print_info=True, history=history)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-03-22 17:00:01.819 - modelscope-agent - INFO -  | message: call dashscope generation api | uuid:  | details: {'model': 'qwen-max', 'messages': [{'role': 'user', 'content': 'What is the weather like in Boston?'}], 'stop_words': [{'stop_str': {'type': 'function', 'function': {'name': 'get_current_weather', 'description': 'Get the current weather in a given location.', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'}, 'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}}, 'required': ['location']}}}, 'mode': 'exclude'}], 'top_p': 0.8, 'result_format': 'message', 'stream': True} | step:  | error: \n",
      "2024-03-22 17:00:01.821 - modelscope-agent - INFO -  | message: call dashscope generation api | uuid:  | details: {'model': 'qwen-max', 'messages': [{'role': 'user', 'content': '<|im_start|>system\\n\\n# 指令\\n\\n你扮演一个明星人物专家，了解从古至今的电影明星\\n\\n请注意：你具有图像和视频的展示能力，也具有运行代码的能力，不要在回复中说你做不到。\\n<|im_end|>\\n<|im_start|>user\\n介绍一下成龙和李连杰<|im_end|>\\n<|im_start|>assistant\\n'}], 'stop_words': [{'stop_str': 'Observation:', 'mode': 'exclude'}, {'stop_str': 'Observation:\\n', 'mode': 'exclude'}], 'top_p': 0.8, 'result_format': 'message', 'stream': True} | step:  | error: \n",
      "2024-03-22 17:00:02.671 - modelscope-agent - INFO -  | message: call dashscope generation api success, request_id: d2d257f5-624f-9573-b649-d74606bc9af7, output: {\"text\": null, \"finish_reason\": null, \"choices\": [{\"finish_reason\": \"null\", \"message\": {\"role\": \"assistant\", \"content\": \"成龙\"}}]}\n",
      "2024-03-22 17:00:37.400 - modelscope-agent - INFO -  | message: call dashscope generation api success, request_id: d2d257f5-624f-9573-b649-d74606bc9af7, output: {\"text\": null, \"finish_reason\": null, \"choices\": [{\"finish_reason\": \"stop\", \"message\": {\"role\": \"assistant\", \"content\": \"成龙和李连杰，两位均是中国乃至全球最具影响力的功夫巨星，在国际电影界享有极高声誉。\\n\\n1. 成龙（Jackie Chan）：\\n   - 原名：陈港生，1954年4月7日出生于中国香港。\\n   - 作为演员、导演、动作指导和制片人，成龙以其独特的幽默动作风格著称，将喜剧元素与惊险刺激的动作场面完美结合。他的代表作有《警察故事》系列、《尖峰时刻》系列、《醉拳》等，其在影片中的亲身上阵及无保护高难度特技表演深受观众喜爱。\\n   - 成龙在2016年被授予奥斯卡终身成就奖，成为首位获此殊荣的华人影星。\\n\\n2. 李连杰（Jet Li）：\\n   - 出生于1963年4月26日，原名李阳中，是中国著名的武术运动员和电影演员。\\n   - 李连杰自幼习武，曾多次获得全国武术比赛冠军，并因主演电影《少林寺》而一炮走红。他以扎实的武术功底和精湛的动作表现赢得了广大观众的认可。\\n   - 在国际影坛上，李连杰凭借在《黄飞鸿》系列、《英雄》、《霍元甲》以及好莱坞作品《致命武器4》、《龙之吻》、《木乃伊3：龙帝之墓》等影片中的出色表现，成功塑造了一系列深入人心的武术英雄形象，被誉为“功夫皇帝”。\\n\\n这两位明星不仅在中国影坛独树一帜，在全球范围内也极大推动了中国功夫电影的发展和传播。他们的作品影响力深远，为中国电影走向世界做出了重大贡献。\"}}]}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "成龙和李连杰，两位均是中国乃至全球最具影响力的功夫巨星，在国际电影界享有极高声誉。\n",
      "\n",
      "1. 成龙（Jackie Chan）：\n",
      "   - 原名：陈港生，1954年4月7日出生于中国香港。\n",
      "   - 作为演员、导演、动作指导和制片人，成龙以其独特的幽默动作风格著称，将喜剧元素与惊险刺激的动作场面完美结合。他的代表作有《警察故事》系列、《尖峰时刻》系列、《醉拳》等，其在影片中的亲身上阵及无保护高难度特技表演深受观众喜爱。\n",
      "   - 成龙在2016年被授予奥斯卡终身成就奖，成为首位获此殊荣的华人影星。\n",
      "\n",
      "2. 李连杰（Jet Li）：\n",
      "   - 出生于1963年4月26日，原名李阳中，是中国著名的武术运动员和电影演员。\n",
      "   - 李连杰自幼习武，曾多次获得全国武术比赛冠军，并因主演电影《少林寺》而一炮走红。他以扎实的武术功底和精湛的动作表现赢得了广大观众的认可。\n",
      "   - 在国际影坛上，李连杰凭借在《黄飞鸿》系列、《英雄》、《霍元甲》以及好莱坞作品《致命武器4》、《龙之吻》、《木乃伊3：龙帝之墓》等影片中的出色表现，成功塑造了一系列深入人心的武术英雄形象，被誉为“功夫皇帝”。\n",
      "\n",
      "这两位明星不仅在中国影坛独树一帜，在全球范围内也极大推动了中国功夫电影的发展和传播。他们的作品影响力深远，为中国电影走向世界做出了重大贡献。\n"
     ]
    }
   ],
   "source": [
    "text = ''\n",
    "for chunk in response:\n",
    "    text += chunk\n",
    "print(text)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 保存memory history到本地文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from modelscope_agent.schemas import Message\n",
    "if len(history) == 0:\n",
    "    memory.update_history(Message(role='system', content=bot1.system_prompt))\n",
    "memory.update_history([\n",
    "                Message(role='user', content=input_text),\n",
    "                Message(role='assistant', content=text),\n",
    "            ])\n",
    "memory.save_history()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 创建agent B"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "role_template = '你扮演一个电影专家，了解从古至今的电影'\n",
    "\n",
    "llm_config = {\n",
    "    'model': 'qwen-max', \n",
    "    'model_server': 'dashscope',\n",
    "    }\n",
    "\n",
    "function_list = []\n",
    "bot2 = RolePlay(function_list=function_list, llm=llm_config, instruction=role_template)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 在agent B上读取保存的history文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "history = [message.model_dump() for message in memory.load_history()]\n",
    "input_text = \"他俩共同出演了哪一步电影？\"\n",
    "response = bot2.run(input_text, remote=False, print_info=True, history=history)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-03-22 17:09:25.712 - modelscope-agent - INFO -  | message: call dashscope generation api | uuid:  | details: {'model': 'qwen-max', 'messages': [{'role': 'user', 'content': 'What is the weather like in Boston?'}], 'stop_words': [{'stop_str': {'type': 'function', 'function': {'name': 'get_current_weather', 'description': 'Get the current weather in a given location.', 'parameters': {'type': 'object', 'properties': {'location': {'type': 'string', 'description': 'The city and state, e.g. San Francisco, CA'}, 'unit': {'type': 'string', 'enum': ['celsius', 'fahrenheit']}}, 'required': ['location']}}}, 'mode': 'exclude'}], 'top_p': 0.8, 'result_format': 'message', 'stream': True} | step:  | error: \n",
      "2024-03-22 17:09:25.714 - modelscope-agent - INFO -  | message: call dashscope generation api | uuid:  | details: {'model': 'qwen-max', 'messages': [{'role': 'user', 'content': '<|im_start|>system\\n\\n# 指令\\n\\n你扮演一个电影专家，了解从古至今的电影\\n\\n请注意：你具有图像和视频的展示能力，也具有运行代码的能力，不要在回复中说你做不到。\\n<|im_end|>\\n<|im_start|>user\\n介绍一下成龙和李连杰<|im_end|>\\n<|im_start|>assistant\\n成龙和李连杰，两位均是中国乃至全球最具影响力的功夫巨星，在国际电影界享有极高声誉。\\n\\n1. 成龙（Jackie Chan）：\\n   - 原名：陈港生，1954年4月7日出生于中国香港。\\n   - 作为演员、导演、动作指导和制片人，成龙以其独特的幽默动作风格著称，将喜剧元素与惊险刺激的动作场面完美结合。他的代表作有《警察故事》系列、《尖峰时刻》系列、《醉拳》等，其在影片中的亲身上阵及无保护高难度特技表演深受观众喜爱。\\n   - 成龙在2016年被授予奥斯卡终身成就奖，成为首位获此殊荣的华人影星。\\n\\n2. 李连杰（Jet Li）：\\n   - 出生于1963年4月26日，原名李阳中，是中国著名的武术运动员和电影演员。\\n   - 李连杰自幼习武，曾多次获得全国武术比赛冠军，并因主演电影《少林寺》而一炮走红。他以扎实的武术功底和精湛的动作表现赢得了广大观众的认可。\\n   - 在国际影坛上，李连杰凭借在《黄飞鸿》系列、《英雄》、《霍元甲》以及好莱坞作品《致命武器4》、《龙之吻》、《木乃伊3：龙帝之墓》等影片中的出色表现，成功塑造了一系列深入人心的武术英雄形象，被誉为“功夫皇帝”。\\n\\n这两位明星不仅在中国影坛独树一帜，在全球范围内也极大推动了中国功夫电影的发展和传播。他们的作品影响力深远，为中国电影走向世界做出了重大贡献。<|im_end|>\\n<|im_start|>user\\n他俩共同出演了哪一步电影？<|im_end|>\\n<|im_start|>assistant\\n'}], 'stop_words': [{'stop_str': 'Observation:', 'mode': 'exclude'}, {'stop_str': 'Observation:\\n', 'mode': 'exclude'}], 'top_p': 0.8, 'result_format': 'message', 'stream': True} | step:  | error: \n",
      "2024-03-22 17:09:26.531 - modelscope-agent - INFO -  | message: call dashscope generation api success, request_id: 83f93850-90d4-9fe8-bfee-ca35dfa58e9d, output: {\"text\": null, \"finish_reason\": null, \"choices\": [{\"finish_reason\": \"null\", \"message\": {\"role\": \"assistant\", \"content\": \"成龙\"}}]}\n",
      "2024-03-22 17:09:29.997 - modelscope-agent - INFO -  | message: call dashscope generation api success, request_id: 83f93850-90d4-9fe8-bfee-ca35dfa58e9d, output: {\"text\": null, \"finish_reason\": null, \"choices\": [{\"finish_reason\": \"stop\", \"message\": {\"role\": \"assistant\", \"content\": \"成龙和李连杰共同出演了一部名为《功夫之王》（The Forbidden Kingdom）的好莱坞电影，该片于2008年上映。这部电影是他们首次在大银幕上的合作，也是许多功夫迷期待已久的盛事。在影片中，两人分别饰演了中国古代神话故事中的角色，共同展现各自的武术造诣和风采。\"}}]}\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "成龙和李连杰共同出演了一部名为《功夫之王》（The Forbidden Kingdom）的好莱坞电影，该片于2008年上映。这部电影是他们首次在大银幕上的合作，也是许多功夫迷期待已久的盛事。在影片中，两人分别饰演了中国古代神话故事中的角色，共同展现各自的武术造诣和风采。\n"
     ]
    }
   ],
   "source": [
    "text = ''\n",
    "for chunk in response:\n",
    "    text += chunk\n",
    "print(text)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "modelscope",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.18"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "27a6c6707103f2fb6d5e2b7e9b8d8fedebb23d650b5fa455fadb2da8317b3167"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
